package com.zhihaoliang.moshi.biz.io;

import static com.zhihaoliang.moshi.util.LoggerKt.log;

import android.content.Context;
import android.util.Log;

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

import java.io.File;
import java.io.FileOutputStream;

import okio.BufferedSink;
import okio.Okio;

/**
 * @author 支豪亮
 * @date 2023/1/28 10:39
 */
public class OutputStreamJava {
   public static <T> void outStream(T obj, Context context)  {
       try {
           File file = new File(context.getCacheDir(),"text.txt");
           if(!file.exists()) file.createNewFile();
           log(file.getAbsolutePath() +":" +file.exists());
           FileOutputStream fileOutputStream = new FileOutputStream(file);
           Moshi moshi = new Moshi.Builder().build();
           //根据泛型获取adapter
           JsonAdapter<T> adapter = moshi.adapter((Class<T>) obj.getClass());
           //OutputStream 转化为 Sink.buffer
           BufferedSink out = Okio.buffer(Okio.sink(fileOutputStream));
           //对象数据的写入
           adapter.toJson(out, obj);
           out.flush();
           log("java end");
       }catch (Exception e){
           Log.e("moshi",  e.toString());
       }
    }
}
